<?php
    class WZ_Form
    {
        public static function initCss()
        {
            $css = array(
                'ViewHelper',
                'Errors',
                array('HtmlTag', array('tag' => 'p')),
                array('Label', array('tag' => 'p')),
                array(array('div' => 'HtmlTag'), array('tag' => 'div'))
            );
            return $css;
        }
        public static function initCssHidden()
        {
            $css = array(
                'ViewHelper',
                'Errors',
                array('HtmlTag', array('tag' => '')),
                array('Label', array('tag' => '')),
                array(array('' => 'HtmlTag'), array('tag' => ''))
            );
            return $css;
        }
        
        public static function getToken(\Zend_Form $form)
        {
            $expiration = time + 900; //15 minutes
            $hash = sha1($expiration . session_id() . $form->getName());
            self::hidden($form, 'token', $hash);
        }
        
        public static function hidden(\Zend_Form $form, $name, $value = '')
        {
            $$name = new \Zend_Form_Element_Hidden($name);
            $$name->setValue($value);
            $$name->setAttrib('class', 'hidden');
            $$name->setDecorators(self::initCssHidden());
            $form->addElement($$name);
        }
        
        public static function input(\Zend_Form $form, $name, $label = '', $required = true, $value = '')
        {
            if (!strlen($label)) {
                $label = $name;
            }
            $$name = new \Zend_Form_Element_Text($name);
            $$name->setValue($value);
            $$name->setAttrib('class', 'text');
            $$name->setLabel(self::__($label));
            $$name->addFilter('stringTrim');
            $$name->setRequired($required);
            $$name->addValidator('NotEmpty', 0, array('messages' => self::__('Merci de renseigner le champ ' . $label . '.')));
            $$name->setDecorators(self::initCss());
            if (true === $required) {
                $$name->getDecorator('label')->setOption('requiredSuffix', ' * ');
            }
            $form->addElement($$name);
        }
        
        public static function date(\Zend_Form $form, $name, $label = '', $required = true, $value = '')
        {
            if (!strlen($label)) {
                $label = $name;
            }
            $$name = new \Zend_Form_Element_Text($name);
            $$name->setValue($value);
            $$name->setAttrib('class', 'text date_picker');
            $$name->setLabel(self::__($label));
            $$name->setRequired($required);
            $$name->addValidator('NotEmpty', 0, array('messages' => self::__('Merci de renseigner le champ ' . $label . '.')));
            $$name->setDecorators(self::initCss());
            if (true === $required) {
                $$name->getDecorator('label')->setOption('requiredSuffix', ' * ');
            }
            $form->addElement($$name);
        }
        
        public static function password(\Zend_Form $form, $name, $label = '', $required = true, $value = '')
        {
            if (!strlen($label)) {
                $label = $name;
            }
            $$name = new \Zend_Form_Element_Password($name);
            $$name->setValue($value);
            $$name->setAttrib('class', 'text');
            $$name->setLabel(self::__($label));
            $$name->setRequired($required);
            $$name->addValidator('NotEmpty', 0, array('messages' => self::__('Merci de renseigner le champ ' . $label . '.')));
            $$name->setDecorators(self::initCss());
            if (true === $required) {
                $$name->getDecorator('label')->setOption('requiredSuffix', ' * ');
            }
            $form->addElement($$name);
        }
        
        public static function html(\Zend_Form $form, $name, $label = '', $required = true, $value = '')
        {
            if (!strlen($label)) {
                $label = $name;
            }
            $$name = new \Zend_Form_Element_Textarea($name);
            $$name->setValue($value);
            $$name->setLabel(self::__($label));
            $$name->setAttrib('class', 'wysiwygTiny');
            $$name->setRequired($required);
            $$name->addValidator('NotEmpty', 0, array('messages' => self::__('Merci de renseigner le champ ' . $label . '.')));
            $$name->setDecorators(self::initCss());
            if (true === $required) {
                $$name->getDecorator('label')->setOption('requiredSuffix', ' * ');
            }
            $form->addElement($$name);
        }
        
        public static function textarea(\Zend_Form $form, $name, $label = '', $required = true, $value = '')
        {
            if (!strlen($label)) {
                $label = $name;
            }
            $$name = new \Zend_Form_Element_Textarea($name);
            $$name->setValue($value);
            $$name->setLabel(self::__($label));
            $$name->setRequired($required);
            $$name->addValidator('NotEmpty', 0, array('messages' => self::__('Merci de renseigner le champ ' . $label . '.')));
            $$name->setDecorators(self::initCss());
            if (true === $required) {
                $$name->getDecorator('label')->setOption('requiredSuffix', ' * ');
            }
            $form->addElement($$name);
        }
        
        public static function select(\Zend_Form $form, $name, $label = '', $required = true, $value = array())
        {
            if (!strlen($label)) {
                $label = $name;
            }
            $$name = new \Zend_Form_Element_Select($name);
            $$name->addMultiOptions($value);
            $$name->setLabel(self::__(\WZ_Inflector::clean($label)));
            $$name->setAttrib('class', 'styled');
            $$name->setRequired($required);
            $$name->addValidator('NotEmpty', 0, array('messages' => self::__('Merci de renseigner le champ ' . $label . '.')));
            $$name->setDecorators(self::initCss());
            if (true === $required) {
                $$name->getDecorator('label')->setOption('requiredSuffix', ' * ');
            }
            $form->addElement($$name);
        }
        
        public static function captcha(\Zend_Form $form, $name, $label = '')
        {            
            $formName = $form->getName();
            $session = \WZ_Session::getInstance('WZCaptchaCrud');
            $code = \WZ::makeCaptchaWord();
            $image = \WZ::captcha($code);
            $varCodeSetter = 'setCaptchacode';
            $varHashSetter = 'setCaptchahash';
            $session->$varCodeSetter($code);
            $hash = str_replace('.jpg', '', end(explode('/', $image)));
            $session->$varHashSetter($hash);
            \WZ::set('WZCaptchaHash_' . $formName, $hash);
            self::input($form, 'captcha', $label, false);
            $session->save();
        }
        
        public static function submit(\Zend_Form $form, $name, $label = '', $required = true, $value = '')
        {
            if (!strlen($label)) {
                $label = $name;
            }
            $$name = new \Zend_Form_Element_Submit($name);
            $$name->setLabel(self::__($label));
            $$name -> setDecorators(array(
                'ViewHelper',
                array(array('p' => 'HtmlTag'), array('tag' => 'p')),
                array(array('div' => 'HtmlTag'), array('tag' => 'div'))
            ));
            $$name -> setAttrib('class', 'submit');
            $form->addElement($$name);
        }
        
        public static function reset(\Zend_Form $form, $name, $label = '', $required = true, $value = '')
        {
            if (!strlen($label)) {
                $label = $name;
            }
            $$name = new \Zend_Form_Element_Reset($name);
            $$name->setLabel(self::__($label));
            $$name -> setDecorators(array(
                'ViewHelper',
                array(array('p' => 'HtmlTag'), array('tag' => 'p')),
                array(array('div' => 'HtmlTag'), array('tag' => 'div'))
            ));
            $$name -> setAttrib('class', 'reset');
            $form->addElement($$name);
        }
        
        public static function factory(\Zend_Form $form, $action, $method = 'post')
        {
            $form->setAction($action)
            ->setDecorators(
                array(
                    'FormElements',
                    array(
                        'HtmlTag', 
                        array(
                            'tag' => 'fieldset'
                        )
                    ),
                    'Form'
                )
            )
            ->setAttrib('class', 'submit')
            ->setMethod($method);
        }
        
        public static function sanitize($form, $formObj)
        {
            $form = str_replace('<ul class="errors">', '<div class="error">', $form);
            $form = str_replace('</ul>', '</div>', $form);
            $form = str_replace('<li>', '', $form);
            $form = str_replace('</li>', '&nbsp;', $form);
            $formName = $formObj->getName();
            $captchaHash = \WZ::get('WZCaptchaHash_' . $formName);
            if (null !== $captchaHash) {
                $img = \WZ_Url::getHome(false) . 'files/' . $captchaHash . '.jpg';
                $form = str_replace('<input type="text" name="captcha" id="captcha"', '<img alt="" src="' . $img . '" />&nbsp;&nbsp;<input type="text" name="captcha" id="captcha"', $form);
                $seg = \WZ::cut('<input type="text" name="captcha"', '>', $form);
                $newSeg = str_replace('class="text"', 'class="captcha"', $seg);
                $newSeg = str_replace('>', ' />', $newSeg);
                $form = str_replace($seg, $newSeg, $form);
            }
            $submitResetHtml = 'class="reset"></p></div>' . "\n" . '<div><p>' . "\n" . '<label for="submit">&nbsp;</label></p><p><input type="submit"';
            $submitResetHtmlReplace = 'class="reset">&nbsp;<input type="submit"';
            // $form = str_replace('<dt id="challenge-label">&#160;</dt>', '', $form);
            // $form = str_replace('<dd id="challenge-element">', '<tr><td  colspan="2">', $form);
            // $form = str_replace('</dd>', '</td></tr>', $form);
            // $form = str_replace('</td></tr></td></tr>', '</td></tr>', $form);
            $form = str_replace(' *', ' <span class="requireStar">*</span> ', $form);
            $form = str_replace('<fieldset', '<fieldset class="crud"', $form);
            $form = str_replace('<input type="reset"', '<label for="reset">&nbsp;</label></p><p><input type="reset"', $form);
            $form = str_replace('<input type="submit"', '<label for="submit">&nbsp;</label></p><p><input type="submit"', $form);
            $form = str_replace('<>', '', $form);
            $form = str_replace('</>', '', $form);
            $form = str_replace('class="reset"></p></div>', 'class="reset">&nbsp;', $form);
            $form = str_replace('<label for="submit">&nbsp;</label></p><p>', '', $form);
            $seg = \WZ::cut('class="reset">', '<input type="submit"', $form);
            $replace = '&nbsp;';
            $form = str_replace($seg, $replace, $form);
            
            //erreurs
            $tab = explode('<div class="error">', $form);
            for ($i = 1 ; $i < count($tab) ; $i++) {
                list($seg, $dummy) = explode('</div>', trim($tab[$i]), 2);
                $newSeg = str_replace('&nbsp;', '<br />', $seg);
                $form = str_replace($seg, $newSeg, $form);
            }
            
            return $form;
        }
        
        public static function render(\Zend_Form $form)
        {
            $viewForm = $form->render(new \Zend_View);
            $render = self::sanitize($viewForm, $form);
            return $render;
        }
        
        public static function __($str)
        {
            return __($str, false);
        }
    }